﻿using Serilog;
using Sustainalytics.Owin.Extensions;
using System;
using System.Configuration.Abstractions;
using Topshelf;

namespace Sustainalytics.RiskRatings.Service
{
    class Program
    {
        private const string ServiceName = "Sustainalytics.RiskRatings.Service";

        static void Main(string[] args)
        {
            var url = ConfigurationManager.Instance.AppSettings.AppSettingSilent("HostUrl", () => "http://localhost:10280/riskratingserv");
            var useHttps = ConfigurationManager.Instance.AppSettings.AppSettingSilent("UseHttps", () => false);

            if (useHttps)
            {
                var uriBuilder = new UriBuilder(url)
                {
                    Scheme = Uri.UriSchemeHttps,
                    Port = ConfigurationManager.Instance.AppSettings.AppSettingSilent("HttpsPort", () => 443)
                };
                url = uriBuilder.Uri.ToString();
            }

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            HostFactory.Run(x =>
            {
                x.Service<WebAppService>(sc =>
                {
                    sc.ConstructUsing(() => new WebAppService(url));
                    sc.WhenStarted(s => s.Start<Startup>());
                    sc.WhenStopped(s => s.Stop());
                });

                x.RunAsLocalSystem();

                x.SetServiceName(ServiceName);
                x.SetDisplayName(ServiceName);
                x.SetDescription("Hosts the " + ServiceName.Replace(".", " "));
            });
        }

        private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            Console.WriteLine(e.ExceptionObject.ToString());
            Log.Error("{0}",e.ExceptionObject.ToString());
        }
    }
}
